import config from "config";
import events from "events";
import { errLogger, outLogger } from "../common/logger";
import { AppConfig } from "../interface/App";
import { DataSource } from "typeorm";

const dbConfig = config.get<AppConfig["dbConfig"]>("dbConfig");
const rootPath = process.env.NODE_ENV === "development" ? 'src/' : 'dist/src/'
export const MysqlDataSource = new DataSource({
  name: "default",
  type: "mysql" as const,
  host: dbConfig.host,
  username: dbConfig.user,
  password: dbConfig.password,
  port: dbConfig.port,
  database: dbConfig.database,
  insecureAuth: true,
  synchronize: true,
  logging: false,
  charset: "utf8mb4",
  // entities: ["../module/**/*.entity.ts", "../module/**/*.entity.js"],
  // subscribers: ["../subscriber/*.ts", "../subscriber/*.js"],
  // migrations: ["../migration/*.ts", "../migration/*.js"]
  entities: [`${rootPath}module/**/*.entity.ts`, `${rootPath}module/**/*.entity.js`],
  subscribers: [`${rootPath}subscriber/*.ts`, `${rootPath}subscriber/*.js`],
  migrations: [`${rootPath}migration/*.ts`, `${rootPath}migration/*.js`]
})

export const dbEvent = new events.EventEmitter();


function start() {
  MysqlDataSource.initialize()
    .then(() => {
      dbEvent.emit("connected");
      outLogger.info(
        `MySQL: database ${dbConfig.database} connected`
      );
    })
    .catch((error) => {
      errLogger.error(error.message);
      setTimeout(() => {
        start();
      }, 5000)
    });
}
start();
